<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Controller;

use Admin\Data\Common;
use Admin\Data\Config;
use Admin\Entity\System;
use Admin\Form\SystemForm;
use Admin\Service\SystemManager;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;

class SystemController extends AdminActionController
{

    private $translator;
    private $entityManager;
    private $systemManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        SystemManager $systemManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->systemManager    = $systemManager;
    }

    /**
     * 系统设置
     * @return array|\Laminas\Http\Response|\Laminas\View\Model\ViewModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function indexAction()
    {
        $form = new SystemForm();

        $form->get('website_timezone|base')->setValueOptions($this->adminCommon()->timezoneArray());
        $form->get('email_service_type|email')->setValueOptions(Common::emailServiceType($this->translator));
        $form->get('smtp_check|email')->setValueOptions(Common::generalState($this->translator));
        $form->get('smtp_secure_conn|email')->setValueOptions(Common::smtpSecureConn($this->translator));
        $form->get('sms_service_provider|sms')->setValueOptions(Common::smsServiceProvider($this->translator));
        $form->get('goods_group_price_show|goods')->setValueOptions(Common::userGroupPriceType($this->translator));
        $language = Common::readConfigFile('language');
        $form->get('a_language|base')->setValueOptions($language['aLanguage']);
        $form->get('f_language|base')->setValueOptions($language['fLanguage']);

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                foreach ($data as $dataKey => $dataValue) {
                    if(in_array($dataKey, [
                        'shop_favicon|base',
                        'shop_logo|base',
                        'shop_footer_image_1|shop_footer',
                        'shop_footer_image_2|shop_footer',
                        'shop_footer_image_3|shop_footer',
                        'shop_footer_image_4|shop_footer',
                        'shop_footer_image_5|shop_footer'
                    ])) {
                        $dataValue = str_replace(Config::PUBLIC_PATH, '', $dataValue['tmp_name']);
                        if(empty($dataValue)) continue;
                    }

                    $where    = explode('|', $dataKey);
                    $oneSystem= $this->entityManager->getRepository(System::class)->findOneBy(['sysName' => $where[0], 'sysType' => $where[1]]);
                    if($oneSystem) {
                        if($oneSystem->getSysBody() != $dataValue) $this->systemManager->editSystem($oneSystem, $dataValue);
                    } else {
                        $this->systemManager->addSystem(['sysName' => $where[0], 'sysBody' => $dataValue, 'sysType' => $where[1]]);
                    }
                }

                //写入配置文件
                $this->createConfig()->createSystem();

                $this->adminCommon()->addOperLog($this->translator->translate('系统设置 修改成功!'), $this->translator->translate('系统设置'));

                return $this->redirect()->toRoute('admin-system');
            }
        }

        $system = $this->entityManager->getRepository(System::class)->findBaseSystem();
        $systemArray = [];
        if($system) {
            foreach ($system as $value) {
                $systemArray[$value->getSysName().'|'.$value->getSysType()] = $value->getSysBody();
            }
            $form->setData($systemArray);
        }

        return [
            'form' => $form,
            'sales_service' => $systemArray['sales_service|content'],
            'buy_service'   => $systemArray['buy_service|content']
        ];
    }

    /**
     * 删除底部图片
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteSystemFooterImageAction()
    {
        $footerImage = $this->params()->fromPost('footerImage');
        if (!empty($footerImage)) {
            $systemInfo = $this->entityManager->getRepository(System::class)->findOneBy(['sysType' => 'shop_footer', 'sysName' => $footerImage]);
            if ($systemInfo) {
                if ($systemInfo->getSysBody()) $this->adminCommon()->deleteImage($systemInfo->getSysBody());
                $this->systemManager->editSystem($systemInfo, '');
                return new JsonModel(['state' => 'true', 'message' => $this->translator->translate('图片删除成功')]);
            }
        }
        return new JsonModel(['state' => 'false', 'message' => $this->translator->translate('图片删除失败')]);
    }
}